package com.handong.handdemo.base;

import android.content.Context;


import java.io.PrintWriter;
import java.io.StringWriter;
import java.io.Writer;

/**
 * Created by zhongqiu on 2019/12/21.
 */


//全部错误捕捉器
public class CrashHandler implements Thread.UncaughtExceptionHandler {
    //本类实例
    private static CrashHandler mInstance;
    //系统默认的uncatchException
    private Thread.UncaughtExceptionHandler mDefaultException;

    private Context mContext;

    //保证只有一个实例
    public CrashHandler() {
    }

    //单例模式
    public static CrashHandler getInstance() {
        if (mInstance == null) {
            mInstance = new CrashHandler();
        }
        return mInstance;
    }

    //获取系统默认的异常处理器,并且设置本类为系统默认处理器
    public void init(Context ctx) {
        this.mContext = ctx;
        mDefaultException = Thread.getDefaultUncaughtExceptionHandler();
        Thread.setDefaultUncaughtExceptionHandler(this);
    }

    //自定义错误处理器
    private void handlerException(final Throwable ex) {
        if (ex == null) {  //如果已经处理过这个Exception,则让系统处理器进行后续关闭处理
            return;
        }

        //获取错误原因
        Writer writer = new StringWriter();
        PrintWriter printWriter = new PrintWriter(writer);
        ex.printStackTrace(printWriter);
        Throwable cause = ex.getCause();
        while (cause!=null){
            cause.printStackTrace(printWriter);
            cause = cause.getCause();
        }
        printWriter.close();
        String result = writer.toString();
        final String msg= result ;
        //Toast.makeText(mContext, "程序出错:程序将重启！" , Toast.LENGTH_LONG).show();
        //将异常记录到本地的数据库或者文件中.或者直接提交到后台服务器
        //return true;
    }

    @Override
    public void uncaughtException(Thread thread, Throwable ex) {
       handlerException(ex);
            // 如果用户没有处理则让系统默认的异常处理器来处理
       mDefaultException.uncaughtException(thread, ex);
        //AppUtil.showShortToast(mContext,"外出押解全局错误！");
        //RestartApplication();


    }
//    private  void RestartApplication()
//    {
//        Intent intent = this.mContext.getApplicationContext().getPackageManager()
//                .getLaunchIntentForPackage(this.mContext.getApplicationContext().getPackageName());
//        PendingIntent restartIntent = PendingIntent.getActivity(this.mContext.getApplicationContext(), 0, intent, PendingIntent.FLAG_ONE_SHOT);
//        AlarmManager mgr = (AlarmManager)this.mContext.getSystemService(Context.ALARM_SERVICE);
//        mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 1000, restartIntent); // 1秒钟后重启应用
//        System.exit(0);
//    }


}
